<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="用户名" prop="user">
        <el-input
          v-model="queryParams.user"
          placeholder="请输入发件者用户名"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="发件人" prop="fromUser">
        <el-input
          v-model="queryParams.fromUser"
          placeholder="请输入发件人"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="开关" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="配置开关"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="typeList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="邮件配置编号" align="center" prop="id"/>
      <el-table-column label="发件用户名" align="center" prop="user" :show-overflow-tooltip="true"/>
      <el-table-column label="发件人" align="center" prop="fromUser" :show-overflow-tooltip="true"/>
      <el-table-column label="SMTP地址" align="center" prop="host" :show-overflow-tooltip="true"/>
      <el-table-column label="SMTP端口" align="center" prop="port" :show-overflow-tooltip="true"/>
      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">

          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-promotion"
            @click="handleTestSend(scope.row)"
          >测试发送
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="user">
          <el-input v-model="form.user" placeholder="请输入发件用户名"/>
          <span style="color: #C0C0C0;margin-left: 10px;">发件者用户名 默认为发件人邮箱前缀</span>
        </el-form-item>
        <el-form-item label="发件人" prop="fromUser">
          <el-input v-model="form.fromUser" placeholder="请输入发件人"/>
          <span style="color: #C0C0C0;margin-left: 10px;">发件人（必须正确，否则发送失败）</span>
        </el-form-item>
        <el-form-item label="授权码" prop="pass">
          <el-input v-model="form.pass" type="password" placeholder="请输入授权码"/>
          <span style="color: #C0C0C0;margin-left: 10px;">邮箱授权码（必须正确，否则发送失败）</span>
        </el-form-item>
        <el-form-item label="SMTP地址" prop="host">
          <el-input v-model="form.host" placeholder="请输入发件人"/>
          <span style="color: #C0C0C0;margin-left: 10px;">邮件服务器SMTP地址 默认为smtp</span>
        </el-form-item>
        <el-form-item label="SMTP端口" prop="port">
          <el-input v-model="form.port" placeholder="请输入发件人"/>
          <span style="color: #C0C0C0;margin-left: 10px;">邮件服务器 SMTP端口 ，默认465或者25</span>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 测试发送-->
    <el-dialog :title="title" :visible.sync="testOpen" width="500px" append-to-body>
      <el-form ref="form" :model="testData" :rules="rules" label-width="100px">
        <el-form-item label="邮件标题" prop="subject">
          <el-input v-model="testData.subject " placeholder="请输入邮件标题"/>
        </el-form-item>
        <el-form-item label="测试账号" prop="toUser">
          <el-input v-model="testData.toUsers" placeholder="请输入测试账号"/>
          <span style="color: #C0C0C0;margin-left: 10px;">多个账号以逗号隔开（xxx@qq.com,yyy@qq.com）</span>
        </el-form-item>
        <el-form-item label="邮件内容" prop="content">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="testData.content"
            maxlength="30"
            show-word-limit
          >
          </el-input>
        </el-form-item>

        <div ref="editor" class="editor"/>
        <el-button :loading="loading" style="margin-left:1.6%;" size="medium" type="primary" @click="sendMail">发送邮件
        </el-button>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import email from "@/api/system/email";

  export default {
    name: "Email",
    data() {
      return {
        AuthoCheck: '北京',
        authTypeList: [{id: 1, value: '北京'}, {id: 1, value: '湖南'}],
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 字典表格数据
        typeList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 是否显示弹出层
        testOpen: false,
        // 状态数据字典
        statusOptions: [],
        // 日期范围
        dateRange: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          user: undefined,
          fromUser: undefined,
          status: undefined
        },
        status: "0",
        // 表单参数
        form: {
          status: null
        },
        testData:{},

        // 表单校验
        rules: {
          user: [
            {required: true, message: "用户名不能为空", trigger: "blur"}
          ],
          fromUser: [
            {required: true, message: "发件人不能为空", trigger: "blur"}
          ],
          pass: [
            {required: true, message: "授权码不能为空", trigger: "blur"}
          ],
          port: [
            {required: true, message: "SMTP端口不能为空", trigger: "blur"}
          ],
          host: [
            {required: true, message: "SMTP地址不能为空", trigger: "blur"}
          ],
          subject: [
            {required: true, message: "标题不能为空", trigger: "blur"}
          ],
          subject: [
            {required: true, message: "测试账号不能为空", trigger: "blur"}
          ],
          subject: [
            {required: true, message: "内容不能为空", trigger: "blur"}
          ]
        }
      };
    },
    created() {
      this.getList();
      this.dict.getDicts("sys_email_status").then(response => {
        this.statusOptions = response.data;
      });
    },
    methods: {
      /** 查询字典类型列表 */
      getList() {
        this.loading = true;
        email.listEmail(this.queryParams).then(response => {
            this.typeList = response.data.records;
            this.total = response.data.total;
            this.loading = false;
          }
        );
      },
      // 字典状态字典翻译
      statusFormat(row, column) {
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          dictId: undefined,
          dictName: undefined,
          dictType: undefined,
          status: "0",
          remark: undefined
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加邮件配置";
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length != 1
        this.multiple = !selection.length
      },
      handleTestSend(row){
        this.testOpen = true;
        this.title = "测试邮件配置";
        this.testData.id = row.id;
      },
      sendMail(){
        email.sendMail(this.testData).then(response => {
          this.testOpen = false;
          this.msgSuccess("发送成功");
        });
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const dictId = row.id || this.ids
        email.getEmail(dictId).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改邮件配置";
        });
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {
              email.updateEmail(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              email.addEmail(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      // 用户状态修改
      handleStatusChange(row) {
        let text = row.status === "0" ? "启用" : "停用";
        this.$confirm('确认要"' + text + '""' + row.user + '"发件者用户名吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return email.changeStatus(row.id, row.status);
        }).then(() => {
          this.msgSuccess(text + "成功");
          this.getList()
        }).catch(function () {
          row.status = row.status === "0" ? "1" : "0";
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const dictIds = row.id || this.ids;
        this.$confirm('是否确认删除字典编号为"' + dictIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return email.delEmail(dictIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有类型数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function () {
          return email.exportEmail(queryParams);
        }).then(response => {
          this.download(response.data);
        })
      }
    }
  };
</script>
